package com.das.extservice.connector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.das.exception.DsConnectorException;

/**
 * 
 * @author chihang
 * Mysql连接器的实例
 *
 */
public class MysqlDsConnector extends DsConnector{
	
	/**
	 * JDBC连接MySQL，这里的数据库操作是操作远程数据集群，故而单独使用JDBC
	 */
	private Connection conn;
	
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	public MysqlDsConnector(String host, int port, String visitName, String visitPasswd) {
		super(host, port, visitName, visitPasswd);
	}
	
	/**
	 * 这个方法抓取给定数据源的资源信息
	 * @return Mysql数据源的资源限定符列表
	 */
	@Override
	public List<String> fetch() throws DsConnectorException {
		
		String[] schemaBlackList = {
			"performance_schema",
			"information_schema",
			"mysql",
		};
		
		List<String> resourceList = new ArrayList<String>();
		
		try {
			conn = DriverManager.getConnection(
					"jdbc:mysql://" + host + ":" + port + "/information_schema", 
					visitName, 
					visitPasswd);
			
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery("SELECT * FROM COLUMNS");
			
			while(rs.next()){
				boolean found = false;
				for(String schema : schemaBlackList){
					if(rs.getString("TABLE_SCHEMA").toLowerCase().equals(schema)){
						found = true;
						break;
					}
				}
				if(found == false){
					System.out.println(
							host + ":" + port + "::" + 
							rs.getString("TABLE_SCHEMA") + "::" + 
							rs.getString("TABLE_NAME") + "::" + 
							rs.getString("COLUMN_NAME"));
					resourceList.add(
							host + ":" + port + "::" + 
							rs.getString("TABLE_SCHEMA") + "::" + 
							rs.getString("TABLE_NAME") + "::" + 
							rs.getString("COLUMN_NAME"));
				}
				
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DsConnectorException("创建连接器失败.");
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new DsConnectorException("关闭连接器失败.");
			}
		}
		
		return resourceList;
	}
	
	public static void main(String[] args) {
		DsConnector dsConnector = new MysqlDsConnector("127.0.0.1", 3306, "root", "123456");
		try {
			List<String> resourceList = dsConnector.fetch();
			System.out.println(resourceList);
		} catch (DsConnectorException e) {
			e.getMessage();
		}
	}
}
